﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using UIT.Style;
using System.Windows;

#if !SILVERLIGHT
namespace UIT.WPF.Converters
#else
namespace UIT.Silverlight.Converters
#endif
{
    class UnitConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Unit unit = (Unit)value;
            if (targetType == typeof(GridLength))
            {
                if (!unit.IsEmpty)
                    return Convert(unit);
                return new GridLength(1, GridUnitType.Star);
            }
            if (targetType == typeof(double))
            {
                if (!unit.IsEmpty)
                    if (unit.Type == UnitType.Pixel)
                        return Convert(unit).Value;
                    else
                        throw new NotSupportedException();
                else
                    return new GridLength(1, GridUnitType.Star);
            }
            throw new NotSupportedException();
        }

        public static GridLength Convert(Unit unit)
        {
            if (unit.Type == Style.UnitType.Percentage)
            {
                return new System.Windows.GridLength(unit.Value, System.Windows.GridUnitType.Star);
            }
            else if (unit.Type == Style.UnitType.Pixel)
            {
                if (unit.Value == double.NegativeInfinity)
                    return System.Windows.GridLength.Auto;
                return new System.Windows.GridLength(unit.Value);
            }
            else
                throw new NotSupportedException("unit can only be specified in % or px");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is GridLength)
            {
                GridLength gridLength = ((GridLength)value);
                switch (gridLength.GridUnitType)
                {
                    case GridUnitType.Auto:
                        return new Unit(double.NegativeInfinity, UnitType.Pixel);
                    case GridUnitType.Pixel:
                        return new Unit(gridLength.Value, UnitType.Pixel);
                    case GridUnitType.Star:
                        return new Unit(gridLength.Value, UnitType.Percentage);
                }
            }
            throw new NotSupportedException();
        }
    }
}
